import fs from "fs";
import path from "path";
import { app, BrowserWindow, ipcMain, protocol, Tray, MenuItemConstructorOptions, Menu, nativeImage } from "electron";
import { IAppContainerOptions } from "@anyshare/common/lib/stores";
import qs from "query-string";
import RichClientLog from "@anyshare/common/lib/utils/logHelper";
// import * as Sentry from "@sentry/electron";
import Cluster from "cluster";
import { exec, execFile } from "child_process";
import * as Utils from "../common/utils";

enum SyncDiskState {
    NotRunning = 0, //同步盘没有在运行
    MigratingCache = 1, //同步盘正在迁移缓存
    GetOEMConfig = 2, //获取oem信息
    ComponentInitialization = 3, //组件初始化
    Online = 4, //在线
    Offline = 5, //离线
    Logout = 6, //注销
    Exit = 7, //退出
    Unkonwn = 8, //未知状态
}

const appIndex =
    process.env.NODE_ENV === "development"
        ? "http://127.0.0.1:4019"
        : `file://${path.resolve(__dirname, "index.html")}`;

const resourceDir =
    process.env.NODE_ENV === "development"
        ? path.resolve(__dirname, "../../../electron/resources")
        : path.resolve(__dirname, "../resources");

const devTools = path.resolve(__dirname, process.env.NODE_ENV === "development" ? "../../devtools" : "../devtools");

const log = new RichClientLog();
log.startCrashReport();

let logined: boolean = false;
const syncDiskName = Utils.getSyncDiskName();

let newWorker: boolean = false;
let syncdiskLaunchProtect: boolean = false;
let limitLaunchSyncdiskTimes = 5;
let timer: NodeJS.Timeout;
async function installExtensions() {
    const devtools = fs.readdirSync(devTools);

    devtools.forEach((devtoolId) => {
        const devtoolDir = path.join(devTools, devtoolId);
        if (fs.existsSync(path.join(devtoolDir, "manifest.json"))) {
            BrowserWindow.addDevToolsExtension(devtoolDir);
        }
    });
}

function initTray() {
    let tray: Tray;
    let trayIcon = nativeImage.createFromPath(path.join(resourceDir, "/common/icon.png"));
    if (process.platform === "darwin") {
        trayIcon = trayIcon.resize({ width: 16, height: 16 });
        tray = new Tray(trayIcon);
    } else {
        tray = new Tray(trayIcon);
    }
    if (process.platform === "linux") {
        tray.setToolTip("");
    }
    return tray;
}

function launchSyncDisk(commandid?: string) {
    ipcMain.emit("queryState", commandid);
}

const zhcnTray = {
    exit: "退出",
    logout: "注销",
    about: "关于",
    openNew: "打开新窗口",
    openCache: "打开",
    setting: "设置",
    syncDetail: "同步详情",
    syncDisk: `${syncDiskName.zhcn}`,
};

const zhtwTray = {
    exit: "離開",
    logout: "登出",
    about: "關於",
    openNew: "開啟首頁",
    openCache: "開啟",
    setting: "設定",
    syncDetail: "同步詳情",
    syncDisk: `${syncDiskName.zhtw}`,
};

const enusTray = {
    exit: "Exit",
    logout: "Log out",
    about: "About",
    openNew: "Open Home Page",
    openCache: "Open",
    setting: "Settings",
    syncDetail: "Details",
    syncDisk: `${syncDiskName.enus}`,
};

let currentLanguage = "zh-cn";
let isShowOneLogoutMsgBox = false;
let isShowOneExitMsgBox = false;
let latestDocinfo: any;
function performLogoutOrExit(mainWindow: BrowserWindow | null, action: string) {
    if (process.platform === "win32") {
        ipcMain.emit("queryStateBeforeExit", action);
    } else {
        if (mainWindow) {
            handleLogoutAndExitMsgBox(mainWindow, action);
        }
    }
}
function setTrayContextMenu(mainWindow: BrowserWindow | null, tray: Tray, authed: boolean, isShowAbout: boolean) {
    let currentTray;
    if (currentLanguage === "zh-cn") {
        currentTray = zhcnTray;
    } else if (currentLanguage === "zh-tw") {
        currentTray = zhtwTray;
    } else {
        currentTray = enusTray;
    }
    const trayTemplate: MenuItemConstructorOptions[] = [
        {
            label: currentTray?.exit,
            click: () => {
                performLogoutOrExit(mainWindow, "exit");
            },
        },
    ];

    if (isShowAbout) {
        trayTemplate.splice(0, 0, {
            label: currentTray?.about,
            click: () => {
                mainWindow?.webContents.send("aboutAppVersion");
            },
        });
    }

    if (authed) {
        trayTemplate.splice(1, 0, {
            label: currentTray?.logout,
            click: () => {
                performLogoutOrExit(mainWindow, "logout");
            },
        });

        if (process.platform === "win32") {
            trayTemplate.unshift({
                label: currentTray?.syncDisk,
                submenu: [
                    {
                        label: currentTray?.openCache,
                        click: () => {
                            launchSyncDisk("openCache");
                        },
                    },
                    {
                        label: currentTray?.syncDetail,
                        click: () => {
                            launchSyncDisk("openSyncDiskDetail");
                        },
                    },
                    {
                        label: currentTray?.setting,
                        click: () => {
                            launchSyncDisk("openSetting");
                        },
                    },
                ],
            });
        }

        trayTemplate.unshift({
            label: currentTray?.openNew,
            click: () => {
                mainWindow?.webContents.send("newWindow", true); // 一定是新开主界面窗口
            },
        });
    }
    const menu = Menu.buildFromTemplate(trayTemplate);
    tray.setContextMenu(menu);
}

// 对当前启动参数进行判断处理（isProduction用来区分开发阶段及包阶段）
function handleArgv(argv: string[], PROTOCOL: string) {
    const prefix = `${PROTOCOL}:`;
    const url = argv.find((arg) => arg.startsWith(prefix));
    return url || "";
}

// 对当前启动url进行解析处理
function handleUrl(awakeUrlStr: string, mainWindow: BrowserWindow | null) {
    log.info("对当前启动url进行解析处理" + awakeUrlStr);
    const { searchParams } = new URL(awakeUrlStr);
    const client = searchParams.get("client");
    const docid = searchParams.get("docid");
    const type = searchParams.get("type");
    const route = searchParams.get("route");
    const sel = searchParams.get("sel");
    mainWindow?.webContents.send("launchWithParams", {
        client,
        docid,
        type,
        route,
        sel,
    });
}

// 对接同步盘内的副文档下载
function handleSubDocumentDownload(resJSON: any, mainWindow: BrowserWindow | null) {
    try {
        const subDocInfo = resJSON.content?.detail?.subDocInfo;
        for (let i = 0; i < subDocInfo.length; i += 1) {
            subDocInfo[i].name = path.parse(subDocInfo[i].path).base;
            subDocInfo[i].docid = subDocInfo[i].gns;
            subDocInfo[i].rev = subDocInfo[i].rev;
            subDocInfo[i].docLibType = subDocInfo[i].doclibtype;
            subDocInfo[i].isOpen = subDocInfo[i].isopen ? true : false;
        }
        mainWindow?.webContents.send(
            "downloadSubDocument",
            JSON.stringify({
                fileObjs: subDocInfo,
                isResume: false,
                isOpen: false,
                isFailRetry: false,
                isSyncDisk: true,
                // docLibType: ""
            })
        );
    } catch (e) {
        log.error(e);
    }
}

// 对接同步盘内的文件预览
function handleSyncDiskFilePreview(resJSON: any, mainWindow: BrowserWindow | null) {
    try {
        const previewFileInfo = resJSON.content?.detail;
        mainWindow?.webContents.send("syncDiskFilePreview", JSON.stringify(previewFileInfo));
    } catch (e) {
        log.error(e);
    }
}

function refreshAddon(mainWindow: BrowserWindow | null) {
    if (newWorker) {
        log.info("创建新的worker");
        const worker = Cluster.fork();
        ipcMain.emit("destory");
        worker.send({ commandId: "RegisterReciver", detail: 1 });
        worker.send({ commandId: "getmsg" });
        worker.on("message", (res: any) => {
            const resJSON = JSON.parse(JSON.parse(res));
            log.info(`worker.onMessage:${res}`);
            const commandId = resJSON.content?.commandId;
            if (commandId === "setOpenSyncdiskType") {
                const openWithRichClient = resJSON.content?.detail?.openWithRichClient;
                mainWindow?.webContents.send("setSyncDiskLaunchOption", openWithRichClient);
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "share") {
                const detail = resJSON.content?.detail;
                mainWindow?.webContents.send("syncdiskInvokeShare", detail);
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "copySharedLink") {
                const detail = resJSON.content?.detail;
                mainWindow?.webContents.send("syncdiskInvokeCopySharedLink", detail);
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "sendSubdocInfo") {
                handleSubDocumentDownload(resJSON, mainWindow);
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "sendSubDocPreview") {
                handleSyncDiskFilePreview(resJSON, mainWindow);
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "abnormalExit") {
                limitLaunchSyncdiskTimes > 0 && ipcMain.emit("queryState", "openCache");
                limitLaunchSyncdiskTimes--;
            } else if (commandId === "Logined") {
                //接收到同步盘发出的登录完成的通知
                ipcMain.emit("invokeDelayEvent");
                worker.send({ commandId: "getmsg" });
            } else if (commandId === "openLocation") {
                const docId = resJSON.content?.detail?.docId;
                mainWindow?.webContents.send("syncdiskOpenInRichclient", docId);
                worker.send({ commandId: "getmsg" });
            } else {
                worker.send({ commandId: "getmsg" });
            }
        });
        ipcMain.once("destory", () => {
            worker.destroy();
        });
    }
}

// 处理注销退出窗口
function handleLogoutAndExitMsgBox(mainWindow: BrowserWindow, commandStr: string) {
    if (commandStr === "logout") {
        if (!isShowOneLogoutMsgBox) {
            isShowOneLogoutMsgBox = true;
            mainWindow?.webContents.send("trayLogOut");
        } else {
            mainWindow?.webContents.send("focusLogoutMsgBox");
        }
    } else {
        if (!isShowOneExitMsgBox) {
            isShowOneExitMsgBox = true;
            mainWindow?.webContents.send("trayExit");
        } else {
            mainWindow?.webContents.send("focusExitMsgBox");
        }
    }
}

function syncAwaitAddonRes(mainWindow: BrowserWindow | null) {
    if (Cluster.isMaster) {
        for (let i = 0; i < 2; i++) {
            const worker = Cluster.fork();
            log.info(worker.id + "====pid=====" + worker.process.pid + "进程启动" + worker.isConnected());
            if (worker.id === 2) {
                worker.send({ commandId: "RegisterReciver", detail: 1 });
                worker.send({ commandId: "getmsg" });
                ipcMain.once("destory", () => {
                    worker.destroy();
                });
            } else {
                worker.send({ commandId: "RegisterReciver", detail: 0 });
                ipcMain.on("login", (_event: any, hostname: string, port: number, token: string) => {
                    worker.send({
                        commandId: "login",
                        detail: {
                            url: hostname,
                            port: port,
                            languageName: currentLanguage,
                            token,
                        },
                    });
                    log.info("SendMessage login");
                });
                ipcMain.on("openCache", (_event: any) => {
                    if (process.platform === "win32") {
                        worker.send({
                            commandId: "openCache",
                            detail: {},
                        });
                    }
                    log.info("SendMessage openCache");
                });
                ipcMain.on("waitUntilSyncClientOnline", (_event: any, commandId: string) => {
                    log.info("waitUntilSyncClientOnline " + commandId);
                    ipcMain.once("invokeDelayEvent", () => {
                        log.info("invokeDelayEvent " + commandId);
                        launchSyncDisk(commandId);
                    });
                });
                ipcMain.on("openFile", (_event: any) => {
                    if (process.platform === "win32") {
                        worker.send({
                            commandId: "openFile",
                            detail: latestDocinfo,
                        });
                    }
                    log.info("SendMessage openFile" + JSON.stringify(latestDocinfo));
                });

                ipcMain.on("openSetting", (_event: any) => {
                    if (process.platform === "win32") {
                        worker.send({
                            commandId: "openSetting",
                            detail: {},
                        });
                        log.info("SendMessage openSetting");
                    }
                });

                ipcMain.on("openSyncDiskDetail", (_event: any) => {
                    if (process.platform === "win32") {
                        worker.send({
                            commandId: "openSyncDiskDetail",
                            detail: {},
                        });
                        log.info("SendMessage openSyncDiskDetail");
                    }
                });
                ipcMain.on("onLogined", (_event: any, token: string) => {
                    worker.send({
                        commandId: "logined",
                        detail: {
                            token,
                        },
                    });
                    log.info("SendMessage logined");
                    ipcMain.emit("refreshAddon");
                });
                ipcMain.on("startSyncDisk", (event: any) => {
                    worker.send({
                        commandId: "startSyncDisk",
                        detail: event,
                    });
                    //10s内不处理启动,且防止同步盘启动失败不能再次启动
                    syncdiskLaunchProtect = true;
                    setTimeout(() => {
                        syncdiskLaunchProtect = false;
                    }, 10000);
                    log.info("SendMessage startSyncDisk");
                });
                ipcMain.on("existLowVersion", (event: any) => {
                    worker.send({
                        commandId: "existLowVersion",
                        detail: event,
                    });
                    log.info("SendMessage existLowVersion");
                });
                ipcMain.on("queryState", (event: any) => {
                    worker.send({
                        commandId: "queryState",
                        detail: event,
                    });
                    log.info("SendMessage queryState");
                });
                ipcMain.on("queryStateBeforeExit", (event: any) => {
                    worker.send({
                        commandId: "queryStateBeforeExit",
                        detail: event,
                    });
                    timer = setTimeout(() => {
                        exec("taskkill /f /im tray.exe");
                    }, 3000);

                    log.info("SendMessage queryStateBeforeExit");
                });
                ipcMain.on("checkIfFileUncached", (event, filePath: string) => {
                    if (process.platform === "win32") {
                        // Windows
                        worker.send({
                            commandId: "IsUnCachedFile",
                            detail: filePath,
                        });
                        ipcMain.once("checkEmptyFile", (isEmpty: any) => {
                            event.returnValue = !!isEmpty;
                        });
                    }
                });
                ipcMain.on("changeLanguage", (_event: any, language: string) => {
                    worker.send({
                        commandId: "languageSwitched",
                        detail: {
                            languageName: language,
                        },
                    });
                });
                ipcMain.on("reLanuch", (_event: any) => {
                    newWorker = true;
                    worker.send({
                        commandId: "relaunch",
                    });
                    log.info("SendMessage reLaunch");
                });
                ipcMain.on("exit", (_event: any) => {
                    try {
                        worker.send({
                            commandId: "quit",
                            detail: {},
                        });
                        log.info("SendMessage quit");
                    } catch (error) {
                        log.info("通信异常，SyncDisk未退出");
                        app.exit();
                    }
                });
                ipcMain.on("tokenUpdate", (_event: any, token: string) => {
                    worker.send({
                        commandId: "tokenUpdate",
                        detail: {
                            token,
                        },
                    });
                    log.info("SendMessage tokenUpdate");
                });
                ipcMain.on("syncClientOpen", (_event: any, docId: string, docPath: string, selectFile: number) => {
                    latestDocinfo = {
                        docId,
                        docPath: docPath.replace(/\//g, "\\"),
                        selectFile,
                    };
                    launchSyncDisk("openFile");
                });
                ipcMain.on("syncClientOpenDir", (_event: any, docId: string, docPath: string) => {
                    latestDocinfo = {
                        docId: docId,
                        docPath: docPath.replace(/\//g, "\\"),
                    };
                    launchSyncDisk("openDir");
                });
            }
            worker.on("message", (res: any) => {
                const resJSON = JSON.parse(JSON.parse(res));
                log.info(`worker.onMessage:${res}`);
                const commandId = resJSON.content?.commandId;
                if (commandId === "setOpenSyncdiskType") {
                    const openWithRichClient = resJSON.content?.detail?.openWithRichClient;
                    mainWindow?.webContents.send("setSyncDiskLaunchOption", openWithRichClient);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "share") {
                    const detail = resJSON.content?.detail;
                    mainWindow?.webContents.send("syncdiskInvokeShare", detail);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "copySharedLink") {
                    const detail = resJSON.content?.detail;
                    mainWindow?.webContents.send("syncdiskInvokeCopySharedLink", detail);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "startSyncDisk") {
                    mainWindow?.webContents.send("startSyncDisk", resJSON.content?.detail);
                } else if (commandId === "existLowVersion") {
                    const res = resJSON.content?.detail?.res;
                    const params = resJSON.content?.detail?.params;
                    if (!res) {
                        ipcMain.emit("startSyncDisk", params);
                    } else {
                        //存在旧版本的同步盘
                        mainWindow?.webContents.send("syncdiskVersionConflict");
                    }
                } else if (commandId === "Logined") {
                    //接收到同步盘发出的登录完成的通知
                    ipcMain.emit("invokeDelayEvent");
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "abnormalExit") {
                    newWorker = true;
                    limitLaunchSyncdiskTimes > 0 && ipcMain.emit("queryState", "openCache");
                    limitLaunchSyncdiskTimes--;
                } else if (commandId === "relaunch") {
                    mainWindow?.webContents.send("afterRelaunch");
                } else if (commandId === "quit") {
                    log.info("同步盘已退出，主程序退出");
                    app.exit();
                } else if (commandId === "openLocation") {
                    const docId = resJSON.content?.detail?.docId;
                    mainWindow?.webContents.send("syncdiskOpenInRichclient", docId);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "queryState") {
                    const res = resJSON.content?.detail?.res;
                    const params = resJSON.content?.detail?.params;
                    log.info(`QueryState:${res}`);
                    switch (res) {
                        case SyncDiskState.Unkonwn:
                        case SyncDiskState.NotRunning:
                        case SyncDiskState.Logout:
                        case SyncDiskState.GetOEMConfig:
                        case SyncDiskState.ComponentInitialization:
                            if (!syncdiskLaunchProtect) {
                                ipcMain.emit("existLowVersion", params);
                            } else {
                                log.info("Invalid launch operation");
                            }
                            break;
                        default:
                            if (params === "openFile" || params === "openDir") {
                                setTimeout(() => {
                                    worker.send({
                                        commandId: params,
                                        detail: latestDocinfo,
                                    });
                                }, 1000);
                            } else {
                                worker.send({
                                    commandId: params,
                                    detail: {},
                                });
                            }
                            log.info(`SendMessage ${params}`);
                            break;
                    }
                } else if (commandId === "queryStateBeforeExit") {
                    clearTimeout(timer);
                    const res = resJSON.content?.detail?.res;
                    const params = resJSON.content?.detail?.params;
                    log.info(`QueryState:${res}`);
                    if (res === 1) {
                        mainWindow?.webContents.send("stopExecution");
                    } else {
                        if (mainWindow) {
                            handleLogoutAndExitMsgBox(mainWindow, params);
                        }
                    }
                } else if (commandId === "sendSubdocInfo") {
                    handleSubDocumentDownload(resJSON, mainWindow);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "sendSubDocPreview") {
                    handleSyncDiskFilePreview(resJSON, mainWindow);
                    worker.send({ commandId: "getmsg" });
                } else if (commandId === "IsUnCachedFile") {
                    ipcMain.emit("checkEmptyFile", resJSON.content?.detail?.params);
                } else if (commandId === "syncdiskOffline") {
                    exec("taskkill /f /im tray.exe");
                } else {
                    worker.send({ commandId: "getmsg" });
                }
            });
        }
    }
}

function main() {
    let mainWindow: BrowserWindow | null;

    if (process.env.NODE_ENV === "production") {
        const sourceMapSupport = require("source-map-support");
        sourceMapSupport.install();
    }

    if (process.env.NODE_ENV === "development" || process.env.DEBUG_PROD === "true") {
        require("electron-debug")();
    }

    // 协议名
    const PROTOCOL = "anyshare7";
    // 与渲染进程通讯事件名
    const OPENREDNDER = "open-render";
    // 对当前主机进行注册/写入协议
    app.setAsDefaultProtocolClient(PROTOCOL);

    // 如果唤起的时候，没有其他实例，则以当前实例作为主实例，处理唤起url中的参数
    // handleArgv(process.argv, PROTOCOL, process.env.NODE_ENV === "production" ? true : false, awakeUrlInfo);

    app.on("open-url", (_event, urlStr) => {
        log.info("mac启动参数", urlStr);
        if (logined) {
            handleUrl(urlStr, mainWindow);
        } else {
            ipcMain.once("handleArgsAfterLaunch", () => {
                handleUrl(urlStr, mainWindow);
            });
        }
    });

    // 主进程通讯监听渲染进程派发的OPENRENDER事件
    ipcMain.on(OPENREDNDER, () => {
        // 并发送当前唤起应用的数据
        mainWindow?.webContents.send(OPENREDNDER);
    });

    app.on("certificate-error", (event, _webContents, _url, _error, _certificate, callback) => {
        event.preventDefault();
        callback(true);
    });
    const isSingleInstance = app.requestSingleInstanceLock();

    // const isSecondInstance = app.makeSingleInstance(() => {
    //     mainWindow?.webContents.send("newWindow");
    // });

    // Sentry.init({ dsn: "http://c2146f07ebd54cf1a68c3696bfa71da7@192.168.57.31:9000/3" });
    if (!isSingleInstance) {
        app.quit();
        return;
    }

    app.on("second-instance", (_event, commanLine, _workingDirectory) => {
        log.info("接受启动参数", commanLine);
        if (process.platform === "darwin") return;
        const openCache = commanLine.some((item) => item === "-opencache");
        const linkActivate = commanLine.some((item) => item.startsWith(`${PROTOCOL}://`));
        if (openCache) {
            mainWindow?.webContents.send("needLaunchSyncDisk");
        } else if (linkActivate) {
            if (logined) {
                handleUrl(handleArgv(commanLine, PROTOCOL), mainWindow);
            } else {
                const signinWindow = BrowserWindow.getAllWindows().filter((window) =>
                    window.webContents.getURL().match("signin")
                );
                if (signinWindow.length !== 0 && signinWindow[0].isVisible && _event) {
                    signinWindow[0].show();
                }
                ipcMain.once("handleArgsAfterLaunch", () => {
                    handleUrl(handleArgv(commanLine, PROTOCOL), mainWindow);
                });
            }
        } else {
            mainWindow?.webContents.send("newWindow", false);
        }
    });

    app.once("ready", () => {
        if (process.env.NODE_ENV === "development" || process.env.DEBUG_PROD === "true") {
            installExtensions();
        }

        protocol.registerStringProtocol("anyshare", ({ url }, _callback) => {
            const { query, url: baseURL } = qs.parseUrl(url);
            const { code, state } = query;
            const { windowId } = JSON.parse(Buffer.from(state as string, "base64").toString("utf-8"));
            const targetWebContents = BrowserWindow.fromId(windowId)!.webContents;
            switch (baseURL) {
                case "anyshare://oauth2/login/callback":
                    targetWebContents.send("authorizationcode", code);
                    // callback();
                    break;
                case "anyshare://oauth2/logout/callback":
                    targetWebContents.send("oauth2sessionlogout");
                    // callback();
                    break;
            }
        });

        protocol.registerFileProtocol("anyshare-resource", (request, _callback) => {
            const urlext = request.url.substring(29);
            const {
                query: { windowid },
            } = qs.parseUrl(urlext);

            mainWindow?.webContents.send("launchofficeonline", { url: urlext, id: windowid });
        });

        mainWindow = new BrowserWindow({
            maximizable: true,
            show: false,
            closable: false,
            x: 0,
            y: 0,
            webPreferences: {
                devTools: true,
                nodeIntegration: true,
                nodeIntegrationInWorker: true,
                webSecurity: false,
                enableRemoteModule: true,
            },
            hasShadow: true,
        });

        let tray = initTray();
        tray.on("click", () => {
            if (process.platform === "win32") {
                mainWindow?.webContents.send("newWindow", false);
            }
        });

        if (process.platform !== "darwin") {
            log.info("第一个实例", process.argv);
            if (process.platform === "win32") {
                Cluster.setupMaster({
                    exec: path.resolve(
                        __dirname,
                        process.env.NODE_ENV === "development" ? "../../public/worker.js" : "../public/worker.js"
                    ),
                });
                Cluster.on("exit", (worker) => {
                    log.info(worker.id + "进程结束");
                });
                syncAwaitAddonRes(mainWindow);
            }
            const specificParams = process.argv.some(
                (item) => item === "-opencache" || item.startsWith(`${PROTOCOL}://`)
            );
            if (specificParams) {
                log.info("第一个实例带参数启动");
                mainWindow.webContents.on("did-finish-load", () => {
                    app.emit("second-instance", null, process.argv);
                });
            }
        }

        mainWindow.loadURL(`${appIndex}#/anyshare/_main`);

        ipcMain.on("appwindowready", (_event: any, windowId: number) => {
            mainWindow?.webContents.send("appwindowready", windowId);
        });

        ipcMain.on("currentLanguage", (_event: any, language: string, isShowAbout: boolean) => {
            currentLanguage = language;
            setTrayContextMenu(mainWindow, tray, false, isShowAbout);
        });

        ipcMain.on("mustOpenNewMainWindow", () => {
            mainWindow?.webContents.send("newWindow", true); // 一定是新开主界面窗口
        });

        ipcMain.on("changeLanguage", (_event: any, language: string) => {
            currentLanguage = language;
            setTrayContextMenu(mainWindow, tray, true, true);
            setTimeout(() => {
                if (app.isPackaged && process.env.APPIMAGE) {
                    const options = {
                        args: process.argv.slice(1).concat(["--relaunch"]),
                        execPath: process.execPath,
                    };
                    execFile(process.env.APPIMAGE, options.args);
                    app.exit(0);
                }
                app.relaunch();
                mainWindow?.webContents.send("trayExitWithout");
            }, 1000);
        });

        ipcMain.on("performExit", () => {
            performLogoutOrExit(mainWindow, "exit");
        });
        ipcMain.on("performLogout", () => {
            performLogoutOrExit(mainWindow, "logout");
        });
        ipcMain.on("refreshAddon", () => {
            refreshAddon(mainWindow);
        });

        ipcMain.on("blankwindowready", (_event: any, windowId: number) => {
            mainWindow?.webContents.send("blankwindowready", windowId);
        });

        ipcMain.on("launchapp", (_event: any, appUrl: string, options: IAppContainerOptions) => {
            mainWindow?.webContents.send("launchapp", appUrl, options);
        });

        ipcMain.on("globaleventbus", (_event: any, senderId: number, type: string, ...args: any[]) => {
            mainWindow?.webContents.send("globaleventbus", senderId, type, ...args);
        });

        ipcMain.on("eventbus", (_event: any, senderId: number, type: string, ...args: any[]) => {
            mainWindow?.webContents.send("eventbus", senderId, type, ...args);
        });

        ipcMain.on("cancleAnyShareLayout", (_event: any, isCancel: boolean) => {
            isShowOneLogoutMsgBox = isCancel;
        });

        ipcMain.on("cancleAnyShareExit", (_event: any, isCancel: boolean) => {
            isShowOneExitMsgBox = isCancel;
        });

        ipcMain.on("launchSyncClient", () => {
            launchSyncDisk("openCache");
        });

        ipcMain.on("exit", (_event: any) => {
            if (process.platform != "win32") {
                app.exit();
            }
        });

        ipcMain.on("reLanuch", (_event: any) => {
            setTrayContextMenu(mainWindow, tray, false, true);
            logined = false;
            if (process.platform != "win32") {
                mainWindow?.webContents.send("afterRelaunch");
            }
        });

        ipcMain.on("renewTrayContext", () => {
            logined = true;
            setTrayContextMenu(mainWindow, tray, true, true);
        });

        ipcMain.on("openFileInLinux", (_event: any, filepath: string) => {
            exec(`xdg-open '${filepath}'`);
        });

        ipcMain.on("checkIfFileUncached", (event, filePath: string) => {
            if (process.platform != "win32") {
                log.info("0kb文件" + filePath);
                event.returnValue = false;
            }
        });
    });

    app.on("before-quit", (event) => {
        event.preventDefault();
        if (mainWindow) {
            handleLogoutAndExitMsgBox(mainWindow, "exit");
        }
    });

    app.on("gpu-process-crashed", () => {
        log.error("the GPU process crashes or is killed");
    });

    app.on("renderer-process-crashed", () => {
        log.error("renderer process unexpectedly dissapears,This is normally because it was crashed or killed.");
    });

    app.on("activate", () => {
        mainWindow?.webContents.send("createWindow");
    });

    app.on("web-contents-created", (_e, webContents) => {
        webContents.on("new-window", (event, url) => {
            if (
                url.indexOf("https://www.eisoo.com/documents?document=anyshare-user-manual&title=error-codes") > -1 ||
                url.indexOf("http://beian.miit.gov.cn") > -1 ||
                url.indexOf("http://www.beian.gov.cn/portal/registerSystemInfo?recordcode") > -1 ||
                url.includes("PowerPointView=SlideShowView") ||
                url.includes("/Agreement/UserAgreement/ServiceAgreement") ||
                url.includes("/Agreement/Privacy/Privacy") ||
                url === "about:blank#blocked"
            ) {
                event.preventDefault();
            }
        });
    });
}

main();
